var nowindex=1;
var fileindex="";
$(function() {
	if(getUrlParam("applyno") == null){
	bindDict('flagcode', 'DM_F01_15', null, null);  //船旗国
	bindDict('portcode', 'DM_F01_5', null, null);   //船籍港
	bindDict('markcode', 'DM_F05_10', null, null);   //海船内河标志
	bindDict('typecode', 'DM_F01_6', null, null);   //船舶种类
	bindDict('areacode', 'DM_F01_3', null, null);    //核定航区
	}
	
	// 时间控件						
	$('#building').datetimepicker({
		language : 'zh-CN',
		minView: "month", //选择日期后，不会再跳转去选择时分秒 
		format: 'yyyy-mm-dd',
		weekStart : 1,
		todayBtn : 1,
		autoclose : 1,
		todayHighlight : 1,
		startView : 2,
		forceParse : 0
	});
	
	initFileInput('upload', null, null);
	
//	上传文本控件关闭事件 -- 清除内容
	$('#fileuploadmodal').on('hide.bs.modal', function () {
        setTimeout(function(){
        	$('.fileinput-remove').trigger('click');
        }, 1000);
	})
	
	$('#submitRecord').click(function(){
		saveRecord(true);
	})	
	$('#saveRecord').click(function(){
		saveRecord(false);
	})
	
	if(getUrlParam('applyno') == null || getUrlParam('applyno') == ''){
		$('#submitRecord').hide();
	}
});

function saveRecord(issubmit){
	var param = {};
	var applyData = $('#Apply').serializeObject();
	var businessData = $('#Business').serializeObject();
	var recordcertificateDate=$("#recordcertificate").serializeObjectArray();
	param['itemno']  = getUrlParam('itemno');
	param['Apply'] = applyData;
	param['Business'] = businessData;
	param['Business']['recordcertificate']=recordcertificateDate;
	param['issubmit'] = issubmit;
	
	if($("#recordid").val()!=null && $("#recordid").val()!=''){
		param['Business']['recordid']=$("#recordid").val();
	}
	
	console.log(JSON.stringify(param));
	if(!checkData(param)){
		return;
	}
	
	if(getUrlParam('change') == '1')
		delete applyData['applyid'];
	
	$.ajax({ 
		method: 'post',
		url: projectPath + 'business/apply.do',
		data: JSON.stringify(param),
        dataType: 'json',  
        contentType:'application/json;charset=UTF-8', 
		success: function(data){
			var msa = data.info;

			var applyno = "";
			if(data.result == 1){
				if(issubmit)
					msa = "提交成功！";
				else
					msa = "保存成功！";
				
				applyno = data.datas.applyno;
				msa += '<br/><span style="color:red;">申请单号是：' + applyno + '</span>'; 
			}
			
			$.confirm({
			    title: '提示!',
			    content: msa,
			    confirmButton: '确定',
			    cancelButton: '取消',
			    confirm: function(){
			    	if(msa.indexOf("未登录") < 0){
			    		var itemno = $('[name="itemno"]').val();
			    		window.location.href = "detail.html?applyno=" + applyno + "&itemno=" + itemno;
			    	}
			    }
			});
		}
	});
}

function addrecordcertificate(){
	
	var html = ''+
	  '	<tr>'+
	  '		<td>'+
	  '			<select class="form-control" name="certificatetype" id="certificatetype'+nowindex+'">'+
	  '		<input type="hidden"  class="form-control" name="recordtype"  value="2"></td>'+
	  '		<td>'+
	  '			<input type="date" class="form-control" name="issuedate" id="issuedate'+nowindex+'">'+
	  '		</td>'+
	  '		<td>'+
	  '			<input type="date" class="form-control" name="effectivedate" id="effectivedate'+nowindex+'">'+
	  '		</td>'+
//	  '		<td>'+
//	  '			是<input type="checkbox" onclick="permanentchange(this)" name="permanent"  value="1" id="permanenty'+nowindex+'">否<input type="checkbox" onclick="permanentchange(this)" name="permanent" checked value="0" id="permanentn'+nowindex+'">'+
//	  '		</td>'+
	  '		<td id="filename'+ nowindex +'"></td>'+
	  '	    <td><button type="button"  onclick="openModal('+nowindex+')" class="btn btn-success" ><span class="glyphicon glyphicon-upload"></span>上传</button>'+
	  '			<input type="hidden" id="upload'+nowindex+'" class="form-control" name="fileid"  value=""></td>'+
	  '		<td>'+
	  '			<button type="button"  onclick="deleterecordcertificate(this)" class="btn btn-danger btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-minus"></span></button>'+
	  '		</td>'+
	  '	</tr>';	
	
	$("#recordcertificate").find('tbody').append(html);
	bindDict("certificatetype"+nowindex,"DM_DWBAZSLX",null);
	nowindex++;
}
function deleterecordcertificate(button){
	$(button).parent().parent().remove();
}

function openModal(index){
	fileindex=index;
	$('#fileuploadmodal').modal('show');
}

function initFileInput(ctrlcss, params, data) {
	
	var urls = [];
	if(data != null){
		for(var i = 0; i < data.length; i++){
			urls[i] = data[i].url;
		}
	}
    var control = $('.' + ctrlcss);
    control.fileinput({
        theme: 'explorer-fa',
        language: 'zh', //设置语言
        uploadUrl: projectPath + "share/upload_fileinput.do", //上传的地址
//         allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
        uploadAsync: true, //默认异步上传
        showUpload: true, //是否显示上传按钮
        showRemove : true, //显示移除按钮
        showPreview : true, //是否显示预览
        showCaption: false,//是否显示标题
        browseClass: "btn btn-primary", //按钮样式
        enctype: 'multipart/form-data',
        validateInitialCount:true,
        overwriteInitial: false,
        initialPreviewAsData: true,
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
        initialPreview: urls,
	    initialPreviewConfig: data,

    }).on('filepreupload', function(event, data, previewId, index) {     //上传中
        var form = data.form, files = data.files, extra = data.extra,
        response = data.response, reader = data.reader;
        console.log(JSON.stringify(data.form));
        console.log('文件正在上传');
    }).on("fileuploaded", function (event, data, previewId, index) {    //一个文件上传成功
    	 console.log('文件上传成功！');
         
         var resultData = data.response;
         var fileid = resultData.datas[0].fileid;
         var filename = '<p id="'+ fileid +'"><a href="/gahCSP/share/downFiles.do?filename='+ resultData.datas[0].filename +'&fileid='+ fileid +'">' + resultData.datas[0].filename + '</a><span class="glyphicon glyphicon-remove" style="color:red;cursor:pointer;" onclick="deleteFile(\''+ fileindex +'\', \''+ fileid +'\')"></span></p>';
         var fileids = $('#upload' + fileindex).attr("value");
         var filenames = $('#filename' + fileindex).html();
         if(fileids == ''){
         	fileids = fileid;
         	filenames = filename;
         }
         else{
         	fileids += ',' + fileid;
         	filenames += filename;
         }

         $('#upload' + fileindex).attr("value", fileids);
         
         $('#filename' + fileindex).html(filenames);

     	 $('#fileuploadmodal').modal('hide');
     	
    }).on('fileerror', function(event, data, msg) {  //一个文件上传失败
        console.log('文件上传失败！'+data.id);
    }).on('filepredelete', function(event, key, jqXHR, data) {  
        alert(key);   
        return;
    });  
}

function deleteFile(index, fileid){
	var fileidsNew = "";
	var fileids = $('#upload' + index).attr('value');
	for(var i=0; i<fileids.split(',').length; i++){
		if(fileids.split(',')[i] != fileid){
			fileidsNew += fileids.split(',')[i] + ',';
		}
	}
	if(fileids.split(',').length > 0)
		fileidsNew = fileidsNew.substring(0, fileidsNew.length - 1);
	
	$('#' + fileid).remove();

	$('#upload' + index).attr('value', fileidsNew);
}